package com.sphd.beautysalon.activitys.foods;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sphd.beautysalon.info.LoginInfo;
import com.sphd.beautysalon.info.SortInfo;
import com.sphd.beautysalon.R;
import com.sphd.beautysalon.adapters.FoodTypeAdapter;
import com.sphd.beautysalon.base.BaseActivity;
import com.sphd.beautysalon.base.RestaurantUrl;
import com.sphd.beautysalon.info.RestaurantInfo;
import com.sphd.beautysalon.presenter.FoodTypePresenterImpl;
import com.sphd.beautysalon.utils.Constant;
import com.sphd.beautysalon.view.FoodTypeView;
import com.wzh.frame.utils.StringUtils;

import org.litepal.crud.DataSupport;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/*
* 菜品管理的界面
* */
public class FoodtypeActivity extends BaseActivity implements FoodTypeView {
    RestaurantInfo restaurantInfo;
    Intent intent;
    Bundle bundle;
    FoodTypePresenterImpl foodTypePresenter;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.my_recy)
    RecyclerView myRecy;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    @BindView(R.id.content_foodtype)
    RelativeLayout contentFoodtype;
    FoodTypeAdapter foodTypeAdapter;
    LoginInfo loginInfo;
    @BindView(R.id.add_food)
    ImageView addFood;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_foodtype);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(view -> finish());
        mySwf.setOnRefreshListener(() -> {
            addData();
        });
        myRecy.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

                bundle.putSerializable(Constant.SORTINFOS, (Serializable) baseQuickAdapter.getData());
                bundle.putSerializable(Constant.SORTINFO, (Serializable) baseQuickAdapter.getItem(i));
                bundle.putInt(Constant.ITEMPOS, i);
                intent.putExtras(bundle);
                intent.setClass(context, FoodMenuActivity.class);
                startActivityForResult(intent, 1);
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                showEditDialog((SortInfo) adapter.getItem(position), 1);
            }

            @Override
            public void onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemLongClick(adapter, view, position);
                if (isCg_has_storemanager(restaurantInfo) && isSuperManager(loginInfo)) {
                    toast("店长会去操作，您不用费心了");
                } else {
                    showDelFoodType((SortInfo) adapter.getItem(position), position);
                }

            }
        });

    }

    /**
     * 删除菜品提示框
     */
    private void showDelFoodType(final SortInfo info, final int position) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                context);
        alertDialogBuilder
                .setTitle("删除提示")
                .setMessage("只有在分类下没有服务的时候才能删除")
                .setCancelable(false)
                .setIcon(getResources().getDrawable(R.mipmap.ic_menu_delete))
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                if (info.getDishes() == 0) {
                                    foodTypePresenter.sendEdit(RestaurantUrl.Httptitle
                                            + RestaurantUrl.Delfoodtype + "sortid=" + info.getId() + "&cgid=" + info.getCgid(),dialog);

                                } else {
                                    toast(info.getSort() +
                                            "还有" + info.getDishes()
                                            + "个服务，不能删除");
                                }

                            }
                        })
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    private void showEditDialog(SortInfo item, int type) {
        View promptsView = getView(R.layout.layout_edittextdialog);
        final EditText userInput = (EditText) promptsView
                .findViewById(R.id.input);
        userInput.setHint("服务名称");
        AlertDialog alertDialog = setAlertDialog(promptsView);
        alertDialog.setTitle("编辑服务类别:");
        if (type == 1) {
            userInput.setText(item.getSort());
        }
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                    if (StringUtils.isEmpty(userInput.getText().toString())) {
                        awalysShow(dialogInterface);
                        toast("分类不能为空");
                        userInput.setError("分类不能为空");
                    } else {
                        if (type==1){
                            if (userInput.getText().equals("未分类")) {
                                toast("未分类不可编辑");
                                awalysShow(dialogInterface);
                            } else {
                                if (userInput.getText().toString().equals(item.getSort())) {
                                    dialogInterface.dismiss();
                                } else {
                                    foodTypePresenter.sendEdit(RestaurantUrl.Httptitle + RestaurantUrl.Changefoodtype +
                                            "sortid=" + item.getId() + "&sort=" + StringUtils.utf8Encode(userInput.getText().toString().trim()), dialogInterface);

                                }
                            }
                        }else {
                            foodTypePresenter.sendEdit(RestaurantUrl.Httptitle + RestaurantUrl.Addfoodtype +
                                    "cgid=" + restaurantInfo.getId() + "&sort=" +
                                    StringUtils.utf8Encode(userInput.getText().toString().trim()),
                                    dialogInterface);

                        }
                    }
            }
        });
        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        alertDialog.show();

    }

    private void awalysShow(DialogInterface dialog) {
        try {
            Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(dialog, false); // false - 使之不能关闭(此为机关所在，其它语句相同)

        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }


    private void initView() {
        setTitleBar(toolbar, "服务设置");
        intent = getIntent();
        bundle = intent.getExtras();
        loginInfo = DataSupport.findLast(LoginInfo.class);
        restaurantInfo = (RestaurantInfo) bundle.getSerializable(Constant.RESTAURANTSINFO);
        foodTypePresenter = new FoodTypePresenterImpl(this);
        if (isCg_has_storemanager(restaurantInfo)&&isSuperManager(loginInfo)){
            addFood.setVisibility(View.GONE);
        }

        initAdapter();
        addData();
    }

    private void addData() {
        foodTypePresenter.addData(RestaurantUrl.Httptitle + RestaurantUrl.Showfoodtype + "cgid=" + restaurantInfo.getId());
    }

    private void initAdapter() {
        setRefresh(mySwf);
        setRecy(myRecy);
        foodTypeAdapter = new FoodTypeAdapter(R.layout.item_food_type, new ArrayList<>(), restaurantInfo, loginInfo);
        myRecy.setAdapter(foodTypeAdapter);
    }

    @Override
    public void recRes(List<SortInfo> sortInfos) {
        foodTypeAdapter.setNewData(sortInfos);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0) {
            addData();
        }
    }

    @OnClick(R.id.add_food)
    public void onClick() {
        showEditDialog(new SortInfo(),2);
    }

    @Override
    public void recEditRes(int res, DialogInterface dialog) {
        if (res == 1) {
            toast("提交成功");
            addData();
        } else {
            toast("提交失败请重试");
        }
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
        mySwf.setRefreshing(false);
    }
}
